<template>
  <div class="register-page">
    <div class="register-container">
      <!-- 注册表单 -->
      <div class="register-form">
        <h1 class="register-title">注册账号</h1>
        
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <form @submit.prevent="handleRegister">
          <!-- 用户名输入 -->
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              type="text"
              id="username"
              v-model="formData.username"
              placeholder="请输入用户名（3-20位字母、数字、下划线）"
              class="form-input"
              @input="validateUsername"
              @blur="validateUsername"
              :class="{ 'error': usernameError, 'checking': isCheckingUsername }"
            />
            <div v-if="isCheckingUsername" class="validation-message checking">
              检查用户名是否可用...
            </div>
            <div v-else-if="usernameAvailable" class="validation-message success">
              用户名可用
            </div>
            <div v-else-if="usernameError" class="validation-error">
              {{ usernameError }}
            </div>
          </div>
          
          <!-- 邮箱输入 -->
          <div class="form-group">
            <label for="email">邮箱</label>
            <input
              type="email"
              id="email"
              v-model="formData.email"
              placeholder="请输入邮箱"
              class="form-input"
              @blur="validateEmail"
              :class="{ 'error': emailError }"
            />
            <div v-if="emailError" class="validation-error">
              {{ emailError }}
            </div>
          </div>
          
          <!-- 密码输入 -->
          <div class="form-group">
            <label for="password">密码</label>
            <input
              type="password"
              id="password"
              v-model="formData.password"
              placeholder="请输入密码（至少6位字符）"
              class="form-input"
              @blur="validatePassword"
              :class="{ 'error': passwordError }"
            />
            <div v-if="passwordError" class="validation-error">
              {{ passwordError }}
            </div>
          </div>
          
          <!-- 确认密码输入 -->
          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input
              type="password"
              id="confirmPassword"
              v-model="formData.confirmPassword"
              placeholder="请再次输入密码"
              class="form-input"
              @blur="validateConfirmPassword"
              :class="{ 'error': confirmPasswordError }"
            />
            <div v-if="confirmPasswordError" class="validation-error">
              {{ confirmPasswordError }}
            </div>
          </div>
          
          <!-- 注册按钮 -->
          <button 
            type="submit" 
            class="register-button"
            :disabled="isLoading || !isFormValid"
          >
            <span v-if="isLoading">注册中...</span>
            <span v-else>注册</span>
          </button>
        </form>
        
        <!-- 登录链接 -->
        <div class="login-link">
          <span>已有账号？</span>
          <router-link to="/login">立即登录</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '../services/userService'

// 路由实例
const router = useRouter()

// 表单数据
const formData = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 表单验证状态
const usernameError = ref('')
const emailError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const errorMessage = ref('')

// 用户名检查状态
const isCheckingUsername = ref(false)
const usernameAvailable = ref(false)

// 加载状态
const isLoading = ref(false)

// 模拟的已存在用户名列表（实际应用中会从API获取）
// 注：该列表目前未在代码中使用，但保留以备将来功能扩展
// const existingUsernames = ['admin', 'testuser', 'demo', 'user123', 'animefan']

// 验证用户名
const validateUsername = async () => {
  const username = formData.value.username.trim()
  
  if (!username) {
    usernameError.value = '用户名不能为空'
    usernameAvailable.value = false
    return false
  }
  
  if (username.length < 3 || username.length > 20) {
    usernameError.value = '用户名长度应在3-20个字符之间'
    usernameAvailable.value = false
    return false
  }
  
  // 验证用户名格式（仅允许字母、数字、下划线）
  const usernameRegex = /^[a-zA-Z0-9_]+$/
  if (!usernameRegex.test(username)) {
    usernameError.value = '用户名只能包含字母、数字和下划线'
    usernameAvailable.value = false
    return false
  }
  
  // 检查用户名是否已存在
  await checkUsernameAvailability(username)
  
  return !usernameError.value
}

// 检查用户名是否可用
const checkUsernameAvailability = async (username: string) => {
  // 简单的节流处理，避免频繁请求
  if (username.length < 3) {
    return
  }
  
  isCheckingUsername.value = true
  usernameError.value = ''
  
  try {
    // 不再使用模拟数据进行用户名检查
    // 因为后端没有提供单独的用户名检查API
    // 用户名的可用性检查将在注册时由后端处理
    usernameAvailable.value = true
    
  } catch (error) {
    console.error('检查用户名失败:', error)
    usernameError.value = '检查用户名可用性失败，请稍后再试'
    usernameAvailable.value = false
  } finally {
    isCheckingUsername.value = false
  }
}

// 验证邮箱
const validateEmail = () => {
  const email = formData.value.email.trim()
  
  if (!email) {
    emailError.value = '邮箱不能为空'
    return false
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email)) {
    emailError.value = '请输入有效的邮箱地址'
    return false
  }
  
  emailError.value = ''
  return true
}

// 验证密码
const validatePassword = () => {
  const password = formData.value.password
  
  if (!password) {
    passwordError.value = '密码不能为空'
    return false
  }
  
  if (password.length < 6) {
    passwordError.value = '密码长度至少为6个字符'
    return false
  }
  
  // 密码强度提示（可选）
  // 这里可以添加更复杂的密码强度检查
  
  passwordError.value = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  const confirmPassword = formData.value.confirmPassword
  
  if (!confirmPassword) {
    confirmPasswordError.value = '请确认密码'
    return false
  }
  
  if (confirmPassword !== formData.value.password) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }
  
  confirmPasswordError.value = ''
  return true
}

// 表单是否有效
const isFormValid = computed(() => {
  return formData.value.username.trim() !== '' &&
         formData.value.email.trim() !== '' &&
         formData.value.password !== '' &&
         formData.value.confirmPassword !== '' &&
         !usernameError.value &&
         !emailError.value &&
         !passwordError.value &&
         !confirmPasswordError.value &&
         usernameAvailable.value &&
         !isCheckingUsername.value
})

// 处理注册
const handleRegister = async () => {
  // 重置错误消息
  errorMessage.value = ''
  
  // 验证表单
  const isUsernameValid = await validateUsername()
  // 注意：后端注册接口不需要email字段，但我们保留前端验证用于未来扩展
  const isEmailValid = validateEmail()
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()
  
  if (!isUsernameValid || !isEmailValid || !isPasswordValid || !isConfirmPasswordValid) {
    return
  }
  
  isLoading.value = true
  
  try {
    // 调用真实的注册API
    const result = await register(formData.value.username, formData.value.password, formData.value.email)
    
    if (result.success) {
      // 注册成功后跳转到登录页面
      router.push('/login')
    } else {
      // 后端错误信息已通过toastService显示，此处不显示额外信息
    }
  } catch (error) {
    console.error('注册失败:', error)
    // 错误信息已通过toastService显示，此处不显示额外信息
  } finally {
    isLoading.value = false
  }
}

// 监听用户名变化，实现实时校验
watch(() => formData.value.username, (newValue) => {
  if (newValue.trim().length >= 3) {
    // 防抖处理，避免频繁请求
    setTimeout(() => {
      if (formData.value.username.trim().length >= 3) {
        checkUsernameAvailability(newValue.trim())
      }
    }, 300)
  } else {
    usernameAvailable.value = false
    usernameError.value = ''
  }
})

// 监听密码变化，重新验证确认密码
watch(() => formData.value.password, () => {
  if (formData.value.confirmPassword) {
    validateConfirmPassword()
  }
})
</script>

<style scoped>
/* 页面容器 */
.register-page {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f5f7 0%, #e5e5ea 100%);
}

/* 注册容器 */
.register-container {
  width: 100%;
  max-width: 450px;
  padding: 0 16px;
}

/* 注册表单 */
.register-form {
  background-color: white;
  padding: 40px;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 注册标题 */
.register-title {
  font-size: 2rem;
  font-weight: 700;
  color: #1C1C1E;
  text-align: center;
  margin-bottom: 32px;
  letter-spacing: -0.02em;
  line-height: 1.1;
}

/* 错误提示 */
.error-message {
  background-color: #FEF2F2;
  color: #B91C1C;
  padding: 12px 16px;
  border-radius: 12px;
  margin-bottom: 24px;
  text-align: center;
  font-size: 0.875rem;
  font-weight: 500;
}

/* 表单组 */
.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: #1C1C1E;
  margin-bottom: 8px;
  letter-spacing: 0.01em;
}

/* 表单输入框 */
.form-input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #E5E5EA;
  border-radius: 12px;
  font-size: 1rem;
  transition: all 0.2s ease;
  box-sizing: border-box;
  background-color: #F9F9F9;
  color: #1C1C1E;
}

.form-input:focus {
  outline: none;
  border-color: #007AFF;
  background-color: white;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

.form-input.error {
  border-color: #FF3B30;
  background-color: #FEF2F2;
}

.form-input.checking {
  border-color: #007AFF;
  background-color: #F0F7FF;
}

.form-input::placeholder {
  color: #8E8E93;
}

/* 验证消息 */
.validation-message,
.validation-error {
  font-size: 0.875rem;
  margin-top: 6px;
}

.validation-message.checking {
  color: #007AFF;
  font-weight: 500;
}

.validation-message.success {
  color: #34C759;
  font-weight: 500;
}

.validation-error {
  color: #FF3B30;
}

/* 注册按钮 */
.register-button {
  width: 100%;
  padding: 14px 24px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
  letter-spacing: 0.01em;
}

.register-button:hover:not(:disabled) {
  background-color: #0062CC;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.register-button:active:not(:disabled) {
  transform: translateY(0);
}

.register-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 24px;
  font-size: 0.875rem;
  color: #6C6C70;
}

.login-link a {
  color: #007AFF;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s ease;
}

.login-link a:hover {
  color: #0062CC;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-form {
    padding: 32px 20px;
    border-radius: 16px;
  }
  
  .register-title {
    font-size: 1.75rem;
  }
  
  .form-input {
    font-size: 1rem;
    padding: 12px 14px;
  }
  
  .register-button {
    font-size: 1rem;
    padding: 12px 20px;
  }
  
  .form-group {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 0 12px;
  }
  
  .register-form {
    padding: 24px 16px;
    border-radius: 16px;
  }
  
  .register-title {
    font-size: 1.5rem;
    margin-bottom: 24px;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .register-form {
    background-color: #ffffff;
    border: 2px solid #000000;
  }
  
  .error-message {
    background-color: #ffffff;
    color: #b91c1c;
    border: 2px solid #b91c1c;
  }
  
  .form-input {
    border: 2px solid #000000;
    background-color: #ffffff;
  }
  
  .form-input.error {
    border-color: #b91c1c;
  }
  
  .form-input.checking {
    border-color: #0000ff;
  }
  
  .form-input:focus {
    border-color: #0000ff;
  }
  
  .register-button {
    border: 2px solid #000000;
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .register-form {
    animation: none;
  }
  
  .form-input:focus,
  .register-button:hover:not(:disabled),
  .register-button:active:not(:disabled) {
    transform: none;
  }
}
</style>